#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMenuBar>
#include <QStatusBar>
#include <QFile>
#include <QFileDialog>
#include <QDebug>
#include <QFontDialog>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QMenuBar* menubar = this->menuBar();
    this->setMenuBar(menubar);

    QMenu* menu1 = new QMenu("文件");
    QMenu* menu2 = new QMenu("字体");
    QAction* action1 = new QAction("打开");
    QAction* action2 = new QAction("保存");
    menu1->addAction(action1);
    menu1->addSeparator();
    menu1->addAction(action2);
    QAction* action3 = new QAction("设置字体");
    menu2->addAction(action3);
    menubar->addMenu(menu1);
    menubar->addMenu(menu2);

    // 关联糙函数
    connect(action1,&QAction::triggered,this,[this](){
        //打开文件

        // 1. 获取文件名
        QString path = QFileDialog::getOpenFileName();
        qDebug() << path;
        // 2. 打开文件
        QFile file(path);
        file.open(QFile::ReadOnly);
        if(file.isOpen() == false)
        {
            QStatusBar* statusbar = this->statusBar();
            statusbar->showMessage("打开文件失败");
            return;
        }
        // 3. 读取文件
        QString text = file.readAll();
        // 4. 显示文件内容
        ui->textEdit->setText(text);
        // 5. 关闭文件
        file.close();
    });
    connect(action2,&QAction::triggered,this,[this](){
        QString path = QFileDialog::getSaveFileName();
        QFile file(path);
        file.open(QFile::WriteOnly);
        if(file.isOpen() == false)
        {
            QStatusBar* statusbar = this->statusBar();
            statusbar->showMessage("保存文件失败");
            return;
        }
        // 写文件
        QString text = ui->textEdit->toPlainText();
        file.write(text.toUtf8());
        file.close();
    });
    connect(action3,&QAction::triggered,this,[this](){
        bool ok = false;
       QFont font = QFontDialog::getFont(&ok);
       if(!ok)
           return;
       qDebug() << font;
       ui->textEdit->setFont(font);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

